package www.dianbaozu.com.ui.login

import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.lxj.xpopup.core.BasePopupView
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentLoginBinding
import www.dianbaozu.com.ui.ContractActivity
import www.dianbaozu.com.ui.ProxyViewModel
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.ContractEntity
import www.wen.com.common.lib.data.entities.NavigationEntity
import www.wen.com.common.lib.data.entities.RequestRegisterBody
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.NoTitleAdapter
import www.wen.com.common.lib.util.MD5Util
import www.wen.com.common.lib.util.SpUtil
import www.wen.com.common.lib.util.WxUtil

/**
 * @author WEN
 * @Description:启动页面
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class LoginFragment : BaseLoadingFragment<FragmentLoginBinding>(), View.OnClickListener {

    private val loginViewModel: LoginViewModel by viewModels()

    private val proxyViewModel: ProxyViewModel by activityViewModels()

    private val iwxapi by lazy { WxUtil.getIWXAPI(requireActivity()) }

    override val viewModel: BaseViewModel
        get() = loginViewModel

    override fun getLayoutId(): Int = R.layout.fragment_login

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): NoTitleAdapter = NoTitleAdapter(
            requireActivity(),
            isSetTitleBarHeight = true
    )

    override fun lazyInitView() {
        dataBinding.proxyViewModel = proxyViewModel
        dataBinding.loginViewModel = loginViewModel
        dataBinding.slSelectContainer.post {
            dataBinding.slSelectContainer.isSelected = false
        }
        observeObject(KeyHelper.LOGIN_FRAGMENT_KEY, this, NavigationEntity::class.java) {
            nav(this.id, this.bundle)
        }
        observeObject(KeyHelper.LOGIN_FRAGMENT_KEY, this, Boolean::class.java) {
            requireActivity().resetStartDestination(R.navigation.navigation, R.id.mainFragment)
        }
        addBackPressedCallBack()
        showAgreementPopupView()
    }


    private fun showAgreementPopupView() {
        if(SpUtil.decodeBoolean(KeyHelper.MMKV_IS_FIRST_SHOW_AGREEMENT_POPU_VIEW,true)){
            CreateXPopupHelper.createAgreementPopupView(PopupViewEntity().apply {
                isShow = true
                context = requireActivity()
                resultAgreementCallBack = { view: View, s: String, basePopupView: BasePopupView ->
                    when(s){
                        "隐私政策" -> {
                            startActivityAgency(ContractActivity::class.java, Bundle().apply {
                                putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("隐私政策", "隐私政策"))
                            })
                        }

                        "用户协议" -> {
                            startActivityAgency(ContractActivity::class.java, Bundle().apply {
                                putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("用户协议", "用户协议"))
                            })
                        }

                    }
                }
                resultClickCallBack ={ view: View, s: String, basePopupView: BasePopupView ->
                    when(view.id){

                        R.id.tvNotUpDateApp -> {
                            basePopupView.dismiss()
                            finishMyself()
                        }

                        R.id.tvUpDateApp -> {
                            SpUtil.encode(KeyHelper.MMKV_IS_FIRST_SHOW_AGREEMENT_POPU_VIEW,false)
                            basePopupView.dismiss()
                        }

                    }
                }
            })
        }
    }

    /**
     * 返回键直接关闭该页面
     */
    private fun addBackPressedCallBack() {
        requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {

            override fun handleOnBackPressed() {
                actionLeft()
            }
        })
    }

    override fun actionLeft() {
        CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
            context = requireActivity()
            standardAlertPopupViewTitle = getString(R.string.exit)
            isShow = true
            standardAlertPopupViewCancelContent = "取消"
            standardAlertPopupViewConfirmContent = "确认"
            standardAlertPopupViewContent = "确定要退出系统吗？"
            confirmFunction = {
                finishMyself()
            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tvCountryAreaCode -> {
                CreateXPopupHelper.createBottomAreaCodeListPopupView(PopupViewEntity().apply {
                    this.context = requireActivity()
                    isShow = true
                    itac = proxyViewModel.itac.value!!
                    areaCodeList = proxyViewModel.areaCodeEntities.value
                    areaCodeListResultCallBack = {
                        "+${it.code}".also { area ->
                            dataBinding.tvCountryAreaCode.text = area
                            proxyViewModel.itac.value = it.code
                            SpUtil.encode(KeyHelper.MMKV_ITAC, it.code)
                        }
                    }
                })
            }

            R.id.AgreeAgreement -> {
                dataBinding.slSelectContainer.isSelected = !dataBinding.slSelectContainer.isSelected
                loginViewModel.mAgree.set(dataBinding.slSelectContainer.isSelected)
                loginViewModel.mEnableLogin.set(loginViewModel.enableLogin())
            }

            R.id.tvRegistered -> {
//                dataBinding.slSelectContainer.toast {
//                    nav(R.id.action_loginFragment_to_registeFragment)
//                }
                nav(R.id.action_loginFragment_to_registeFragment)
            }

            R.id.tvForgotPassword -> {
                nav(R.id.action_loginFragment_to_forgetPasswordFragment)
            }

            R.id.strUserAgreement -> {
                nav(R.id.action_loginFragment_to_contractFragment, args = Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("用户协议", "用户协议"))
                })
            }

            R.id.strPrivacyAgreement -> {
                nav(R.id.action_loginFragment_to_contractFragment, args = Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("隐私政策", "隐私政策"))
                })
            }

            R.id.btnLogin -> {
                requestRegister()
            }

            R.id.llSMSLogin -> {
                nav(R.id.action_loginFragment_to_SMSLoginFragment)
            }

            R.id.llWeChatLogin -> {
                dataBinding.slSelectContainer.toast {
                    WxUtil.getIWXAPI(requireActivity()).unregisterApp()
                    wxLogin(getString(R.string.please_install_WeChat), iwxapi.isWXAppInstalled) { WxUtil.callWxLogin(iwxapi) }
                }
            }
        }
    }

    private fun wxLogin(msg: String, isInstalled: Boolean, action: (Boolean) -> Unit) {
        if (isInstalled) {
            action.invoke(isInstalled)
        } else {
            toast(msg)
        }
    }


    /**
     * 注册并登陆
     */
    @FlowPreview
    private fun requestRegister() {
        if(loginViewModel.mPhone.get().isNullOrBlank()) {
            toast("手机号码不能为空")
            return
        }
        if(loginViewModel.mPassword.get().isNullOrBlank()) {
            toast("密码不能为空")
            return
        }
        if(!loginViewModel.mAgree.get()!!) {
            toast("请勾选协议")
            return
        }
        loginViewModel.requestRegister(
                RequestRegisterBody(
                        dataBinding.tvPhoneNumber.trimProxy(),
                        MD5Util.MD5(dataBinding.etPassword.trimProxy()),
                )
        ) { loginInfo ->
            if (loginInfo.user.forbidStatus) {
                CreateXPopupHelper.createInformPopupView(PopupViewEntity().apply {
                    isShow = true
                    context = requireActivity()
                    title = getString(R.string.the_count_is_ban)
                    content = "因以下原因,用户「${loginInfo.user.nickName}」 已被封禁：\n\n【${loginInfo.user.forbidReason}】\n\n在 ${loginInfo.user.unForbidTime}之前，该账号不能进行登录"
                    confirmContent = getString(R.string.got_it)
                    confirmFunction = {
                        it.dismiss()
                    }
                })
            } else {
                requireActivity().resetStartDestination(R.navigation.navigation, R.id.mainFragment)
            }
        }
    }

}



